﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Coleotrack.Common.Registration;
using Coleotrack.Data;
using Coleotrack.Properties;
using Coleotrack.Service.Contracts;
using Coleotrack.Service.Registration;
using Coleotrack.Settings;
using Coleotrack.Web;
using Coleotrack.Web.Registration;
using Coleotrack.Core.Helper;
using StructureMap;

namespace Coleotrack
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        public static ApplicationSettingsLoader ApplicationSettingsLoader { get; set; }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new {favicon = @"(.*/)?favicon.ico(/.*)?"});

            routes.MapRoute(
                "Account_Activation",
                "Account/Activate/{username}/{key}",
                new
                {
                    controller = "Account",
                    action = "Activate",
                    username = UrlParameter.Optional,
                    key = UrlParameter.Optional
                }
            );

            routes.MapRoute(
                "PasswordRequest",
                "Account/PasswordRequest/{username}/{token}",
                new
                {
                    controller = "Account",
                    action = "PasswordRequest",
                    username = UrlParameter.Optional,
                    token = UrlParameter.Optional
                }
                );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new
                {
                    controller = "Home",
                    action = "Index",
                    id = UrlParameter.Optional
                }, // Parameter defaults
                new string[] { "Coleotrack.Controllers" }
            );

        }

        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            ApplicationSettingsLoader = new ApplicationSettingsLoader();
            ApplicationSettingsLoader.LoadFrom(Server.MapPath(ApplicationConstants.PathToApplicationSettings));

            if (ApplicationSettingsLoader.Settings.IsInstalled)
            {
                Bootstrapper.BootstrapWithDatabase(ApplicationSettingsLoader.Settings.ConnectionString, false);
                //InitTestData();
            }
            else
            {
                Bootstrapper.BootstrapWithoutDatabase();
            }
        }

        private void InitTestData()
        {
#if DEBUG
            var user = new User
            {
                Name = "tobias.haar",
                Password = "password".Md5(),
                Email = "tobias.haar@alpha2000.de",
                Active = true,
                Created = DateTime.Now,
                Profile = new UserProfile
                {
                    FirstName = "Tobias",
                    LastName = "Haar"
                }
            };

            var user2 = new User
            {
                Name = "matthias.glauch",
                Password = "glochsen".Md5(),
                Email = "matthias.glauch@mg80s.de",
                Active = true,
                Created = DateTime.Now,
                Profile = new UserProfile
                {
                    FirstName = "Matthias",
                    LastName = "Glauch"
                }
            };

            var project = new Project
            {
                ContactPerson = user,
                Abbreviation = "CTRK",
                Name = "Coleotrack",
                Description = "Simple web-based Issue Tracker"
            };

            var project2 = new Project
            {
                ContactPerson = user,
                Abbreviation = "CTRK2",
                Name = "Coleotrack2",
                Description = "Simple web-based Issue Tracker"
            };

            var area = new Area
            {
                Name = "Area 1",
                Parent = null,
                Project = project
            };

            var category = new Category
            {
                Name = "Category 1"
            };

            var priority = new Priority
            {
                Name = "Normal",
                Order = 1
            };

            var release = new Release
            {
                Due = DateTime.Now.AddDays(1),
                Name = "Release 1",
                Project = project
            };
            var status = new Status
            {
                Name = "Pending"
            };

            var tag = new Tag
            {
                Name = "Tag 1"
            };

            var issue = new Issue
            {
                Area = area,
                AssignedTo = user,
                Category = category,
                Description = "Description of the first issue",
                Due = DateTime.Now.AddDays(1),
                Effort = new Effort(),
                Parent = null,
                Priority = priority,
                Project = project,
                ReportedForRelease = release,
                SolvedInRelease = release,
                Status = status,
                Tags = new List<Tag> { tag },
                Title = "Issue No.1"
            };

            var issue2 = new Issue
            {
                Area = area,
                AssignedTo = user2,
                Category = category,
                Description = "Description of the second issue, child issue of Issue No.1",
                Due = DateTime.Now,
                Effort = new Effort(),
                Parent = issue,
                Priority = priority,
                Project = project,
                ReportedForRelease = release,
                SolvedInRelease = release,
                Status = status,
                Tags = new List<Tag> { tag },
                Title = "Issue No.2"
            };

            var userService = ObjectFactory.GetInstance<IUserService>();
            userService.Insert(user);
            userService.Insert(user2);

            var projectService = ObjectFactory.GetInstance<IProjectService>();
            projectService.Insert(project);
            projectService.Insert(project2);

            var areaService = ObjectFactory.GetInstance<IAreaService>();
            areaService.Insert(area);

            var categoryService = ObjectFactory.GetInstance<ICategoryService>();
            categoryService.Insert(category);

            var priorityService = ObjectFactory.GetInstance<IPriorityService>();
            priorityService.Insert(priority);

            var releaseService = ObjectFactory.GetInstance<IReleaseService>();
            releaseService.Insert(release);

            var statusService = ObjectFactory.GetInstance<IStatusService>();
            statusService.Insert(status);

            var issueService = ObjectFactory.GetInstance<IIssueService>();
            issueService.Insert(issue);
            issueService.Insert(issue2);


#endif
        }
    }
}